#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
typedef pair<int,int> pii;
    vector<int> dx={0,0,1,-1};
    vector<int> dy={1,-1,0,0};
    int swimInWater(vector<vector<int>>& grid) {
        int n=grid.size();
        vector<vector<int>> d(n,vector<int>(n,INT_MAX));
        d[0][0]=grid[0][0];
        priority_queue<tuple<int,int,int>,vector<tuple<int,int,int>>,greater<>> q;
        q.emplace(d[0][0],0,0);
        while(!q.empty())
        {
            auto [d_a,x,y]=q.top();
            q.pop();
            if(d_a>d[x][y]) continue;
            for(int i=0;i<4;i++)
            {
                int cx=x+dx[i];
                int cy=y+dy[i];
                if(cx>=0&&cx<n&&cy>=0&&cy<n)
                {
                    int k=max(grid[cx][cy],d[x][y]);
                    if(k<d[cx][cy])
                    {
                        d[cx][cy]=k;
                        q.emplace(k,cx,cy);
                    }
                }
            }
        }
        return d[n-1][n-1];
    }
};